package com.ja.openchat.ui.chat.group.adapter;

import android.graphics.Color;
import android.media.MediaPlayer;
import android.net.Uri;
import android.text.Html;
import android.text.TextUtils;
import android.text.style.ImageSpan;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.SeekBar;
import android.widget.TextView;

import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.Observer;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.request.RequestOptions;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.viewholder.BaseViewHolder;
import com.ja.openchat.R;
import com.ja.openchat.ui.chat.audio.AudioPlayManager;
import com.ja.openchat.ui.chat.audio.IAudioPlayListener;
import com.ja.openchat.views.FullVideoView;
import com.lqr.emoji.MoonUtils;
import com.zy.openchat.App;
import com.zy.openchat.Constants;
import com.zy.openchat.core.manager.TelegramManager;
import com.zy.openchat.core.model.group.GroupSendInfo;
import com.zy.openchat.core.model.group.LocalMessageInfo;
import com.zy.openchat.core.model.setting.PlayInfo;
import com.zy.openchat.util.TimeConvertUtils;
import com.zy.openchat.util.TimeUtils;
import com.zy.openchat.util.UIUtils;
import com.zy.openchat.util.WeChatImageUtils;

import org.jetbrains.annotations.NotNull;

import java.io.File;

public class GroupSendListAdapter extends BaseQuickAdapter<GroupSendInfo, BaseViewHolder> {

    private MutableLiveData<PlayInfo> messageUpdateLiveData = new MutableLiveData<>();;

    protected RequestOptions placeholderOptions = new RequestOptions();
    public GroupSendListAdapter() {
        super(R.layout.adapter_group_send_list);
        addChildClickViewIds(R.id.add_btn);
        placeholderOptions.diskCacheStrategy(DiskCacheStrategy.ALL);
        placeholderOptions.centerCrop();
        placeholderOptions.placeholder(R.drawable.image_chat_placeholder);
    }

    @Override
    protected void convert(@NotNull BaseViewHolder helper, GroupSendInfo sendInfo) {
        helper.setText(R.id.title_users,String.format(getContext().getString(R.string.recipients_format),sendInfo.groupNumber()));
        helper.setText(R.id.userNamesText,sendInfo.userNames());
        TextView messageText = helper.getView(R.id.messageText);
        ImageView messageImage = helper.getView(R.id.messageImage);
        View messageVideo = helper.getView(R.id.messageVideo);
        View audioContentLayout = helper.getView(R.id.audioContentLayout);
        FullVideoView mVideoView = helper.getView(R.id.videoView);
        TextView durationTextView = helper.getView(R.id.durationTextView);
        SeekBar seekBar = helper.getView(R.id.seekBar);
        ImageView ivAudio = helper.getView(R.id.audioImageView);
        LocalMessageInfo messageInfo = sendInfo.messageInfo;

        setMessageTime(messageInfo,helper.getAdapterPosition(),(TextView) helper.getView(R.id.timeTextView));

        messageText.setVisibility(View.GONE);
        messageImage.setVisibility(View.GONE);
        messageVideo.setVisibility(View.GONE);
        audioContentLayout.setVisibility(View.GONE);
        if(messageInfo!=null){
            if(messageInfo.messageType == TelegramManager.MessageType.MessageType_Text){
                messageText.setVisibility(View.VISIBLE);
                if(!TextUtils.isEmpty(messageInfo.content)){
                    if (messageInfo.content.startsWith("<") && messageInfo.content.endsWith(">")) {
                        messageText.setText(Html.fromHtml(messageInfo.content));
                    } else {
                        MoonUtils.identifyFaceExpressionAndAt(getContext(), messageText,messageInfo.content, ImageSpan.ALIGN_BOTTOM,null);
                    }
                }
            }else if(messageInfo.messageType == TelegramManager.MessageType.MessageType_Photo ||
                    messageInfo.messageType == TelegramManager.MessageType.MessageType_Animation){
                messageImage.setVisibility(View.VISIBLE);
                Glide.with(getContext())
                        .load(messageInfo.content)
                        .thumbnail(Glide
                                .with(getContext())
                                .load(R.drawable.image_chat_placeholder))
                        .apply(placeholderOptions)
                        .into(messageImage);
            }else if(messageInfo.messageType == TelegramManager.MessageType.MessageType_Animation
                    ||messageInfo.messageType == TelegramManager.MessageType.MessageType_Video){
                messageVideo.setVisibility(View.VISIBLE);
                int imageSize[] = WeChatImageUtils.getImageSizeByOrgSizeToWeChat( messageInfo.width, messageInfo.height);
                int width = imageSize[0] > 0 ? imageSize[0] : Constants.MEDIA_MAX_WIDTH;
                int height = imageSize[1] > 0 ? imageSize[1] : Constants.MEDIA_MAX_WIDTH;
                messageVideo.getLayoutParams().width = width;
                messageVideo.getLayoutParams().height = height;
                mVideoView.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
                    @Override
                    public void onPrepared(MediaPlayer mp) {
                        mp.setOnInfoListener(new MediaPlayer.OnInfoListener() {
                            @Override
                            public boolean onInfo(MediaPlayer iMediaPlayer, int what, int i1) {
                                if (what == MediaPlayer.MEDIA_INFO_VIDEO_RENDERING_START)
                                    mVideoView.setBackgroundColor(Color.TRANSPARENT);
                                return true;
                            }
                        });
                        mp.setVolume(0f, 0f);
                        mp.start();
                    }
                });
                mVideoView.setVideoPath(messageInfo.content);
                mVideoView.start();
            }else if(messageInfo.messageType == TelegramManager.MessageType.MessageType_Audio){
                audioContentLayout.setVisibility(View.VISIBLE);
                durationTextView.setText(messageInfo.duration + "''");

                messageUpdateLiveData.observeForever(new Observer<PlayInfo>() {
                    @Override
                    public void onChanged(PlayInfo playInfo) {
                        if (playInfo != null && playInfo.totalLenght > 0&&playInfo.groupSendInfoId == sendInfo.id) {
                            seekBar.setSecondaryProgress(playInfo.secendProssed);
                            seekBar.setProgress(playInfo.currentPosition);
                            if (!playInfo.isPlaying) {
                                seekBar.setProgress(0);
                                ivAudio.setActivated(playInfo.isPlaying);
                            }
                        }
                    }
                });
                if(toPlayAudioMessage!=null&&toPlayAudioMessage.groupSendInfoId == sendInfo.id){
                    ivAudio.setActivated(toPlayAudioMessage.isPlaying);
                    seekBar.setClickable(false);
                    seekBar.setEnabled(false);
                    seekBar.setFocusable(false);
                    seekBar.setOnTouchListener(new View.OnTouchListener() {
                        @Override
                        public boolean onTouch(View v, MotionEvent event) {
                            //直接消费掉触摸事件
                            return true;
                        }
                    });
                }

            }
        }

    }


    protected void setMessageTime(LocalMessageInfo item, int position,TextView timeTextView) {
        long msgTime = item.date;
        if (position > 0) {
            LocalMessageInfo preMsg = getItem(position - 1).messageInfo;
            long preMsgTime = preMsg.date;
            if (!TimeConvertUtils.formatDate10(msgTime).equals(TimeConvertUtils.formatDate10(preMsgTime))) {
                timeTextView.setVisibility(View.VISIBLE);
                timeTextView.setText(TimeUtils.getMsgFormatTimeForYYMMDD(msgTime));
            } else {
                timeTextView.setVisibility(View.GONE);
            }
        } else {
            timeTextView.setVisibility(View.VISIBLE);
            timeTextView.setText(TimeUtils.getMsgFormatTimeForYYMMDD(msgTime));
        }
    }
    private PlayInfo toPlayAudioMessage;

    public void playAudioMessage(GroupSendInfo message) {
        if (message == null || message.messageInfo.messageType!= TelegramManager.MessageType.MessageType_Audio) {
            return;
        }

        if (toPlayAudioMessage != null && toPlayAudioMessage.groupSendInfoId == message.id) {
            AudioPlayManager.getInstance().stopPlay();
            toPlayAudioMessage = null;
            return;
        }

        toPlayAudioMessage = new PlayInfo(message.id);
        File file = new File(message.messageInfo.content);

        if (file == null) {
            return;
        }
        if (file.exists()) {
            playAudio(toPlayAudioMessage, file);
        } else {
            Log.e("ChatInfoViewHolder", "audio not exist");
        }
    }


    private void playAudio(PlayInfo message, File file) {
        Uri uri = Uri.fromFile(file);
        AudioPlayManager.getInstance().startPlay(App.getInstanse(), uri, new IAudioPlayListener() {
            @Override
            public void onStart(Uri var1, int lengthoftime) {
                Log.d("uriisPlaying","onStart==="+var1.toString());
                if (uri.equals(var1)) {
                    message.isPlaying = true;
                    postMessageUpdate(message);
                }else{

                }
            }

            @Override
            public void onStop(Uri var1) {
                Log.d("uriisPlaying","onStop==="+var1.toString());
                if (uri.equals(var1)) {
                    message.isPlaying = false;
                    toPlayAudioMessage = null;
                    postMessageUpdate(message);
                }else{

                }
            }

            @Override
            public void onProgress(Uri var1,int  currentPosition,int secendProssed, int totalLenght) {
//                Log.d("uriisPlaying","onProgress==="+var1.toString());
                if (uri.equals(var1)) {
                    message.isPlaying = true;
                    message.currentPosition = currentPosition;
                    message.secendProssed = secendProssed;
                    message.totalLenght = totalLenght;
                    postMessageUpdate(message);
                }else{

                }
            }

            @Override
            public void onComplete(Uri var1) {
                Log.d("uriisPlaying","onComplete==="+var1.toString());
                if (uri.equals(var1)) {
                    message.isPlaying = false;
                    toPlayAudioMessage = null;
                    postMessageUpdate(message);
                }else{

                }
            }
        });
    }

    private void postMessageUpdate(PlayInfo message) {
        if (message == null) {
            return;
        }
        if (messageUpdateLiveData != null) {
            UIUtils.postTaskSafely(() -> messageUpdateLiveData.setValue(message));
        }
    }


}
